'''
Case Type： 数据库系统
Case Name： 数据库启动前，pg_hba.conf文件损坏
Create At:  2020/06/29
Owner    :  @li-xin12345
Descption:  1.数据库启动前，手工清空配置项；2.重新启动数据库

history：
created： 2020/06/28  created by @li-xin12345
'''
import os
import sys
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import *


class PortOccupied(unittest.TestCase):
    com = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case096.py start------------')
        self.SOURCE_PATH = macro.DB_ENV_PATH
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.pg_hba_path = os.path.join(macro.DB_INSTANCE_PATH, macro.PG_HBA_FILE_NAME)

        self.dbUserNode = Node(node='dbuser')

        self.Constant = Constant()

    def test_set_clear_stop(self):
        try:
            # 停止数据库
            status = self.com.stopDbCluster()
            self.assertTrue(status)

            # 清空pg_hba.conf文件的配置项并启动数据库
            self.log.info('-----------------------------清空pg_hba.conf文件的配置项-----------------------------')
            # 备份文件
            cp_cmd = f"cp {self.pg_hba_path} {self.pg_hba_path}.baktest"
            self.log.info(cp_cmd)
            cp_msg = self.dbUserNode.sh(cp_cmd).result()
            self.assertEqual(cp_msg, '')

            # 清空pg_hba.conf文件
            empty_cmd = f"> {self.pg_hba_path}"
            self.log.info(empty_cmd)
            empty_msg = self.dbUserNode.sh(empty_cmd).result()
            self.assertEqual(empty_msg, '')

            # 启动数据库
            status = self.com.startDbCluster()

            self.assertFalse(status)
        finally:
            # 恢复pg_hba.conf文件
            recover_cmd = f"mv {self.pg_hba_path}.baktest {self.pg_hba_path}"
            self.log.info(recover_cmd)
            recover_msg = self.dbUserNode.sh(recover_cmd).result()
            self.assertEqual(recover_msg, '')

            # 启动数据库
            status = self.com.startDbCluster()
            self.assertTrue(status)

            self.log.info('------------------Opengauss_Reliability_Dbsys_Case096 执行完成------------------------------')
